<template>
	<view class="page">
		<u-empty v-if="list.length == 0" mode="message" icon="http://cdn.uviewui.com/uview/empty/message.png">
		</u-empty>
		<uni-list>
			<uni-list-chat v-for="one in list" :key="one.id" @longpress="showModal(one.id)" :title="one.nickname"
				:note="one.latestMessage" :avatar="one.avatar" badgePositon="left" :badgeText="one.notRead"
				:to="'/pages/private_chat/private_chat?receiverId=' + one.id + '&nickname=' + one.nickname">
				<view class="chat-custom-right">
					<view>{{ getTimeAgo(one.latestTime) }}</view>
				</view>
			</uni-list-chat>
		</uni-list>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				messageId: '',
				show: false,
				userId: '',
				list: [],
			}
		},
		onShow: function() {
			let that = this
			that.isLastPage = false
			that.loadMessageList()
		},
		onLoad() {
			let that = this;
			that.userId = uni.getStorageSync("userId");
			// that.loadMessageList(that)
		},
		onPullDownRefresh() {
			setTimeout(() => {
				uni.redirectTo({
					url: '/pages/my_message/my_message'
				})
			}, 1000)
		},
		methods: {
			getTimeAgo(dateString) {
			    const currentDate = new Date();
			    const targetDate = new Date(dateString);
			    const timeDifference = currentDate - targetDate;
			    const secondsDifference = Math.floor(timeDifference / 1000);
			
			    if (secondsDifference < 60) {
			        return `${secondsDifference}秒前`;
			    } else if (secondsDifference < 3600) {
			        const minutes = Math.floor(secondsDifference / 60);
			        return `${minutes}分钟前`;
			    } else if (secondsDifference < 86400) {
			        const hours = Math.floor(secondsDifference / 3600);
			        return `${hours}小时前`;
			    } else if (secondsDifference < 2592000) {
			        const days = Math.floor(secondsDifference / 86400);
			        return `${days}天前`;
			    } else {
			        const months = Math.floor(secondsDifference / 2592000);
			        return `${months}个月前`;
			    }
			},
			cancelDelete() {
				this.show = false;
			},
			deleteItem() {
				let that = this;
				that.$ajax(that.$url.deleteMessage + "?messageId=" + that.messageId, "GET", null, function(resp) {
					uni.showToast({
						icon: 'none',
						title: '删除成功！'
					})
					that.show = false;
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/my_message/my_message'
						})
					}, 800)
				})
			},
			showModal(id) {
				let that = this;
				that.messageId = id;
				// 触发震动效果
				uni.vibrateShort();
				that.show = true;
			},
			goto(item) {
				let that = this;
				uni.navigateTo({
					url: '/pages/shop_content/shop_content?locationId=' + item.locationId
				})
			},
			loadMessageList: function() {
				let that = this;
				that.$ajax(that.$url.searchPrivateChatObject, "GET", null, function(resp) {
					let result = resp.data.result
					that.list = result;
				})
			}
		}
	}
</script>

<style lang="less">
	@import url("chat_info.less");
</style>